package ext.drawing;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ext.drawing.bean.DrawingsBorrowBean;
import wt.access.AccessControlHelper;
import wt.access.AccessPermission;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.pds.StatementSpec;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.vc.VersionControlHelper;

/**
 * 图文档借阅提交业务类
 * 
 * @author lilin
 * 
 */
@Controller
@RequestMapping({ "/drawingSubmit" })
public class DrawingSubmit {
	@RequestMapping(value = "/submit", method = { RequestMethod.POST, RequestMethod.GET })
	/**
	 * 图文档提交校验以及启动流程
	 * 
	 * @param docNumber
	 * @param time
	 * @param response
	 * @throws Exception
	 */
	public static void drawingSubmit(@RequestParam(value = "docNumber", required = true) String docNumber,
			@RequestParam(value = "time", required = true) String time,
			@RequestParam(value = "cause", required = true) String cause,
			@RequestParam(value = "reason", required = true) String reason, HttpServletResponse response)
			throws Exception {
		JSONObject ob = new JSONObject();
		PrintWriter out = response.getWriter();
		boolean createflag = false;
		WTDocument doc = null;
		WTDocumentMaster docMaster = null;
		try {
			boolean flag = SessionServerHelper.manager.setAccessEnforced(false);// 忽略权限
			QuerySpec qs = new QuerySpec(WTDocumentMaster.class);
			SearchCondition sc = new SearchCondition(WTDocumentMaster.class, WTDocumentMaster.NUMBER,
					SearchCondition.EQUAL, docNumber.trim(), false);
			qs.appendWhere(sc, new int[] { 0 });
			QueryResult qr = PersistenceHelper.manager.find((StatementSpec) qs);// 查询文档编号
			while (qr.hasMoreElements()) {
				docMaster = (WTDocumentMaster) qr.nextElement();
				doc = BorrowWorkflowUtil.getLatestDocument(docMaster);// 获取最新版本
			}
//			WTDocument doc = BorrowWorkflowUtil.getDocByNumber(docNumber);// 查询文档
			
			SessionServerHelper.manager.setAccessEnforced(flag);// 关闭权限

			// SessionServerHelper.manager.isAccessEnforced()&&
			// 对文档的权限校验 已经有权限，无需借阅
			if (AccessControlHelper.manager.hasAccess(SessionHelper.manager.getPrincipal(), doc, AccessPermission.READ)
					&& AccessControlHelper.manager.hasAccess(SessionHelper.manager.getPrincipal(), doc,
							AccessPermission.DOWNLOAD)) {

				String str = "errorOwer";
				ob.put("status", str);
				out.print(ob.toString());
				return;
			}

			createflag = SessionServerHelper.manager.setAccessEnforced(false);// 忽略权限

			String docName = doc.getName();// 文档名称
			String version = VersionControlHelper.getIterationDisplayIdentifier(doc).toString();// 文档版本
			String userName = wt.session.SessionHelper.getPrincipal().getName();// 当前登录人
			List<DrawingsBorrowBean> dbs = BorrowUtil.getDrawingBorrowByNumberAndNameAndVersion(docNumber, userName,
					version);// 获取当前登录人是否已经发生借阅
			// 如果在表中找不到
			if (dbs.size() == 0) {
				Boolean isSave = BorrowUtil.createDrawingBorrow(docName, docNumber, userName, time, version, cause,
						reason);// 保存借阅流程数据
				if (isSave) {// 创建成功之后逻辑
					BorrowWorkflowUtil.startDrawingBorrowWorkFlow(doc);// 启动送审流程，版本为最新版本
					String str = "success";
					ob.put("status", str);
				} else {
					String str = "error";
					ob.put("status", str);
				}
				out.print(ob.toString());
				return;
			} else {// 如果在表中找到
				for (int i = 0; i < dbs.size(); i++) {
					DrawingsBorrowBean db = dbs.get(i);
					String state = db.getBorrowState();// 获得当前状态
					if (BorrowUtil.REVIEW.equals(state)) {// "REVIEW"表示图文档借阅正在审核中
						String str = "errorReview";
						ob.put("status", str);
						out.print(ob.toString());
						return;
					} else if (BorrowUtil.BORROW.equals(state)) {// "BORROW"表示图文档在借阅中
						String str = "errorOwer";
						ob.put("status", str);
						out.print(ob.toString());
						return;
					} else if (BorrowUtil.EXPIRE.equals(state)) {// “EXPIRE”表示图文档借阅已经失效
						Boolean isSave = BorrowUtil.createDrawingBorrow(docName, docNumber, userName, time, version,
								cause, reason);// 保存借阅流程数据
						if (isSave) {
							BorrowWorkflowUtil.startDrawingBorrowWorkFlow(doc);// 启动送审流程，版本为最新版本
							String str = "success";
							ob.put("status", str);
						} else {
							String str = "error";
							ob.put("status", str);

						}
						out.print(ob.toString());
						return;
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SessionServerHelper.manager.setAccessEnforced(createflag);
		}
		out.print(ob.toString());
		return;
	}

}
